<!--//This file is part of the store/retrieve project
//    (http://code.google.com/p/storeretrieve/).
//
//    Store/retrieve is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Store/retrieve is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with store/retrieve. If not, see <http://www.gnu.org/licenses/>.
//-->


<%@ page contentType="text/html; charset=UTF-8"%>
<html>

<%@ page
	import="java.util.Properties,
		java.util.ArrayList,
		java.io.File,
		java.io.FileInputStream,
		org.w3c.dom.*,
		javax.xml.parsers.*,
		javax.xml.xpath.*,
		java.util.HashMap,
		java.lang.StringBuilder,
		javax.xml.transform.dom.DOMSource,
		javax.xml.transform.stream.StreamResult,
		javax.xml.transform.Transformer,
		javax.xml.transform.TransformerFactory,
		javax.xml.transform.OutputKeys,
		de.devcity.storeretrieve.Tools"%>

<%@include file="includes/backend.jsp"%>

<%! 	
	final static String GENERATOR = "OnlineEdit Rev. 1";
	Properties props;
	File file;
	Document doc = null;

	boolean Save(javax.servlet.http.HttpServletRequest request) {
		boolean success;
		
		try {
			DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
            		DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
            		Document newDoc = docBuilder.newDocument();
			Element container = newDoc.createElement("Container");
            		newDoc.appendChild(container);
			Element storage = newDoc.createElement("Storage");
			Element meta = newDoc.createElement("Meta");
			Element e;
		
			container.appendChild(storage);
		
			e = newDoc.createElement("Id");
			storage.appendChild(e);
			e.appendChild(newDoc.createTextNode(request.getParameter("Id")));

                        e = newDoc.createElement("ForeignId");
                        storage.appendChild(e);
                        e.appendChild(newDoc.createTextNode(request.getParameter("ForeignId")));

                        e = newDoc.createElement("Generator");
                        storage.appendChild(e);
                        e.appendChild(newDoc.createTextNode(GENERATOR));

                        e = newDoc.createElement("Revision");
                        storage.appendChild(e);
                        e.appendChild(newDoc.createTextNode("1"));

			container.appendChild(meta);

			String[] fields = {"ImportDate", "DocumentDate", "ProcessedDate", "Sender",
                                "Receiver", "Subject", "Description", "Tags", "Keywords"};

			for(String field : fields) {
				if(request.getParameter(field) != null && !request.getParameter(field).equals("")) {
					e = newDoc.createElement(field);
					meta.appendChild(e);
					e.appendChild(newDoc.createTextNode(request.getParameter(field)));
				}
			}
	
			DOMSource source = new DOMSource(newDoc);
			StreamResult result = new StreamResult(file);
			Transformer transformer = TransformerFactory.newInstance().newTransformer();
			transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			
			//transformer.setOutputProperty(OutputKeys.METHOD, "xml");
			transformer.setParameter("encoding", "UTF-8");
			transformer.transform(source, result);
			doc = newDoc;
			success = true;
		} catch(Throwable ex) { 
			success = false;
			ex.printStackTrace();
		} finally {}	


				
		return success;
	}

%>

<%
	request.setCharacterEncoding("UTF-8");
	props = Tools.loadPropertiesByUser(getServletContext(), request.getRemoteUser()); 

	if(props == null) {
		response.sendRedirect("login.jsp");
	} else {
		HashMap<String, String> queryParms = new HashMap<String, String>();
		queryParms.put("Storage/Id", request.getParameter("id"));
		ArrayList<File> matches = query(props.getProperty("INTERNAL_REPO_PATH"), queryParms);
		if(matches.size() == 1) {
			try {
				//Load XML
				file = new File(matches.get(0).getAbsolutePath() + "/meta.xml");
				DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
				DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
				doc = dBuilder.parse(file);
				doc.getDocumentElement().normalize();

				//Save XML if necessary
				if(request.getParameter("origin") != null && request.getParameter("origin").equals("save")) {
					if(Save(request)) {
						out.println(GENERATOR + ": Saved.<hr />");
					} else {
						out.println(GENERATOR + ": Error while saving! <hr />");
					}
				} else 
					out.println(GENERATOR + " <hr />");

			} catch(Throwable ex) { 
				 ex.printStackTrace();
			} finally {}
		} else throw new Exception("No document found");
	}
%>

<head>
<title>store/retrieve edit client</title>
<link rel="stylesheet" type="text/css"
	href="resources/<%= props.getProperty("CSS") %>" />
<link rel="icon" href="resources/logo-storeretrieve-favicon.png"
	type="image/png" />
</head>
<body>
	<%= Tools.getLogoHtml() %>
	<form method="post" accept-charset="UTF-8"
		action="edit.jsp?id=<%= Tools.getFieldValueFromMetaDOM(doc, "Storage/Id") %>">
		<table>
			<tr>
				<td>ID</td>
				<td><input readonly="readonly" type="text" name="Id" size="50"
					value="<%= Tools.getFieldValueFromMetaDOM(doc, "Storage/Id") %>"></td>
			</tr>
			<tr>
				<td>Foreign ID</td>
				<td><input type="text" name="ForeignId" size="50"
					value="<%= Tools.getFieldValueFromMetaDOM(doc, "Storage/ForeignId") %>"></td>
			</tr>
			<tr>
				<td>Import date</td>
				<td><input readonly="readonly" type="text" name="ImportDate"
					size="10"
					value="<%= Tools.getFieldValueFromMetaDOM(doc, "Meta/ImportDate") %>"></td>
			</tr>
			<tr>
				<td>Document date</td>
				<td><input type="text" name="DocumentDate" size="10"
					value="<%= Tools.getFieldValueFromMetaDOM(doc, "Meta/DocumentDate") %>"></td>
			</tr>
			<tr>
				<td>Processed date</td>
				<td><input type="text" name="ProcessedDate" size="10"
					value="<%= Tools.getFieldValueFromMetaDOM(doc, "Meta/ProcessedDate") %>"></td>
			</tr>
			<tr>
				<td>Sender</td>
				<td><input type="text" name="Sender" size="50"
					value="<%= Tools.getFieldValueFromMetaDOM(doc, "Meta/Sender") %>"></td>
			</tr>
			<tr>
				<td>Receiver</td>
				<td><input type="text" name="Receiver" size="50"
					value="<%= Tools.getFieldValueFromMetaDOM(doc, "Meta/Receiver") %>"></td>
			</tr>
			<tr>
				<td>Subject</td>
				<td><input type="text" name="Subject" size="50"
					value="<%= Tools.getFieldValueFromMetaDOM(doc, "Meta/Subject") %>"></td>
			</tr>
			<tr>
				<td>Description</td>
				<td><input type="text" name="Description" size="50"
					value="<%= Tools.getFieldValueFromMetaDOM(doc, "Meta/Description") %>"></td>
			</tr>
			<tr>
				<td>Tags</td>
				<td><input type="text" name="Tags" size="50"
					value="<%= Tools.getFieldValueFromMetaDOM(doc, "Meta/Tags") %>"></td>
			</tr>
			<tr>
				<td>Keywords</td>
				<td><input type="text" name="Keywords" size="50"
					value="<%= Tools.getFieldValueFromMetaDOM(doc, "Meta/Keywords") %>"></td>
			</tr>
		</table>
		<input type="hidden" name="origin" value="save"> <input
			type="submit" value="Save"> <input type="reset" value="Reset">
	</form>
</body>
</html>

